package com.sl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sl.entity.PageResult;
import com.sl.entity.Result;
import com.sl.entity.StatusCode;
import com.sl.pojo.Role;
import com.sl.pojo.RoleRoute;
import com.sl.pojo.Route;
import com.sl.service.RoleRouteService;
import com.sl.service.RoleService;
import com.sl.service.RouteService;
import com.sl.vo.RouteMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.list.AbstractLinkedList;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("/role")
@Slf4j
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleRouteService roleRouteService;
    @Autowired
    private RouteService routeService;

    /**
     * 查看所有角色Role
     */
   // @RequiresPermissions("role:all")
    @PostMapping("/all")
    public Result allRoles() {
        log.info("查询所有角色");
        List<Role> allRoles = roleService.findAll();
        List<Role> allRoleList=new ArrayList<>();
            for (Role allRole : allRoles) {
                if (!StringUtils.isEmpty(allRole.getRoleName()))
                {allRoleList.add(allRole); }
        }
        PageResult<Role> pageResult = new PageResult((long)allRoleList.size(), allRoleList);

        return new Result(true, StatusCode.OK, "查询角色成功", pageResult);
    }

    @PostMapping("/permission")
    public Result allPermssions(@RequestBody String data){
        log.info("根据角色ID>>>"+ data+"查看权限" );
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer roleId = jsonObject.getInteger("roleId");
        if (null==roleId){return  new Result(false, StatusCode.ERROR,"roleId参数有误");}
        List<RoleRoute> roleRouteList = roleRouteService.findByRoleId(roleId);

        log.info("roleRouteList>>>" + roleRouteList);
        //装route大类。
        Set<Integer> routeFatherIdSets=new HashSet<>();
        Set<Integer> routeSonIdSets=new HashSet<>();

        List<RouteMsg> indexAndFind=new ArrayList<>();
        indexAndFind.add(indexMsg());
        for (RoleRoute roleRoute : roleRouteList) {
            Integer routeId = roleRoute.getRouteId();
            routeSonIdSets.add(routeId);
           // log.info("routeId>>>" + routeId);
            Route route = routeService.findById(routeId);
            if (null == route){return  new Result(false, StatusCode.ERROR,"找不到对应路由");}
            //王宁要求：子类route反向获取爹类。然后封装
            Integer pId = route.getPId();
           // log.info("pId>>>" + pId);
            routeFatherIdSets.add(pId);
            /*RouteMsg routeMsg = DtoRouteMsg(route);
            routeMsgs.add(routeMsg);*/
        }
        log.info("routeFatherIdSets>>>" + routeFatherIdSets);
        log.info("routeSonIdSets>>>" + routeSonIdSets);
        for (Integer routeFatherId : routeFatherIdSets) {
            log.info("FatherId>>>" + routeFatherId);
            //得到route大类
            Route routeFather = routeService.findById(routeFatherId);
          //  log.info("routeFather>>>" + routeFather);
            //Father封装成MSG
            RouteMsg  routeFatherMsg = DtoRouteMsg(routeFather);
            List<RouteMsg> sonRouteMsgList=new ArrayList<>();
            for (Integer routeSonId : routeSonIdSets) {
                Route sonRoute = routeService.findById(routeSonId);
                Integer pId = sonRoute.getPId();
                //如果子类的pid和父类Id 。相等。。封装。
                if (routeFatherId.equals(pId)){
                    log.info("SonId>>>" + routeSonId + "::"+ "FatherId>>>" + routeFatherId);
                    RouteMsg sonRouteMsg = DtoRouteMsg(sonRoute);
                    sonRouteMsgList.add(sonRouteMsg);
                }
            }
            routeFatherMsg.setChildren(sonRouteMsgList);
            System.out.println(routeFatherMsg);
            indexAndFind.add(routeFatherMsg);
        }

        return new Result(true, StatusCode.OK, "查询权限成功",indexAndFind);
    }

    //首页
    public  RouteMsg indexMsg(){
        Route indexRoute = routeService.findById(1);
        RouteMsg indexRouteMsg = DtoRouteMsg(indexRoute);
        Route homeRoute = routeService.findById(2);
        RouteMsg homeRouteMsg = DtoRouteMsg(homeRoute);
        List<RouteMsg> arr=new ArrayList<>();
        arr.add(homeRouteMsg);
        indexRouteMsg.setChildren(arr);
        return indexRouteMsg;
    }

    /**
     * 1新增角色
     * @param data
     * @return
     */
    @PostMapping("/add")
    public Result addRole(@RequestBody String data) {
        log.info("增加角色名称>>>"+ data );
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"POST参数为空");}
        Role role = JSONObject.parseObject(data, Role.class);
        roleService.add(role);
      return new Result(true, StatusCode.OK, "添加角色成功");
    }


    /**角色添加权限成功   给中间表里。。RoleId:1 --- RouteId:2
     */
    @PostMapping("/addRoleRoutes")
    public Result addPermssions(@RequestBody String data){
        log.info("增加角色的权限>>>"+ data );
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer roleId = jsonObject.getInteger("roleId");
        JSONArray routeIds = jsonObject.getJSONArray("routeIds");
        if(null==roleId ||null==routeIds){ return new Result(false, StatusCode.ERROR, "请确定roleId值，routeIds值加S");}
        log.info("roleIds>>>" + roleId +">>>" + "routeIds" +routeIds);
        for (Object routeId : routeIds) {
            RoleRoute roleRoute = new RoleRoute();
            roleRoute.setRoleId(roleId);
            roleRoute.setRouteId((Integer) routeId);
            roleRouteService.add(roleRoute);
        }
        return new Result(true, StatusCode.OK, "角色添加权限成功");
    }
    @DeleteMapping("/deleteRoleRoute")
    public Result deletePermssions(@RequestBody String data){
        log.info("删除角色的权限>>>"+ data );
        RoleRoute roleRoute = JSON.parseObject(data, RoleRoute.class);
        roleRouteService.delete(roleRoute);
        return new Result(true, StatusCode.OK, "角色删除权限成功");
    }

    @DeleteMapping("/info")
    public Result roleInfo(@RequestBody String data) {
        log.info("查询角色>>>");
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        Role byId = roleService.findById(id);
        return new Result(true, StatusCode.OK, "角色查询成功",byId);
    }
    //封装route--》msg
    private RouteMsg DtoRouteMsg(Route route) {
        RouteMsg routeMsg = new RouteMsg();
        routeMsg.setPath(route.getPath());
        routeMsg.setName(route.getName());
        routeMsg.setComponent(route.getComponent());
        routeMsg.setRedirect(route.getRedirect());

        Map<String,Object> map=new HashMap<>();
        map.put("title",route.getTitle());
        map.put("icon",route.getIcon());
        Integer closeableDB = route.getCloseable();
        boolean closeable = true;
        //1为 false 。 0是 显示
        if (closeableDB !=null && closeableDB>0){
            closeable= false;
        }
        map.put("closeable",closeable);

        Integer hiddenDB = route.getHidden();
        boolean hidden = true;
        if (hiddenDB !=null && hiddenDB>0){
            hidden= false;
        }
        map.put("hidden",hidden);
        routeMsg.setMeta(map);
        return routeMsg;
    }

    @DeleteMapping("/deleted")
    public Result  deleteRole(@RequestBody String data){
        log.info("删除角色,且删除中间表对应权限>>>");
        Role role = JSON.parseObject(data, Role.class);
        Integer roleId = role.getId();
        List<RoleRoute> roleRoutes = roleRouteService.findByRoleId(roleId);
        for (RoleRoute roleRoute : roleRoutes) {
            roleRouteService.delete(roleRoute);
        }
        roleService.deleteById(role);
        return new Result(true, StatusCode.OK, "角色删除成功");
    }
}
